package config

import (
	"gopkg.in/yaml.v3"
	"os"
	"path/filepath"
)

// 定义具名结构体类型
type JDKConfig struct {
	InstalledPath string `yaml:"installed_path"`
}

type JarConfig struct {
	StorageDir    string `yaml:"storage_dir"`
	CurrentJar    string `yaml:"current_jar"`
	JarVersionUrl string `yaml:"jar_version_url"`
}

type AutostartConfig struct {
	Enabled bool     `yaml:"enabled"`
	Args    []string `yaml:"args"`
}

type AppConfig struct {
	JDK       JDKConfig       `yaml:"jdk"`
	Jar       JarConfig       `yaml:"jar"`
	Autostart AutostartConfig `yaml:"autostart"`
}

var (
	configPath = filepath.Join(filepath.Dir(os.Args[0]), "config.yaml")
	cfg        *AppConfig
)

func Load() (*AppConfig, error) {
	if cfg != nil {
		return cfg, nil
	}

	data, err := os.ReadFile(configPath)
	if os.IsNotExist(err) {
		return initDefaultConfig()
	}
	if err != nil {
		return nil, err
	}

	err = yaml.Unmarshal(data, &cfg)
	return cfg, err
}

func initDefaultConfig() (*AppConfig, error) {
	cfg = &AppConfig{
		JDK: JDKConfig{
			InstalledPath: "", // 初始为空
		},
		Jar: JarConfig{
			StorageDir:    `C:\hea`,
			CurrentJar:    "",
			JarVersionUrl: "http://192.168.10.49:8080/api/version",
		},
		Autostart: AutostartConfig{
			Enabled: true,
			Args:    []string{"-mode=auto"},
		},
	}
	return cfg, Save(cfg)
}
func Save(cfg *AppConfig) error {
	data, err := yaml.Marshal(cfg)
	if err != nil {
		return err
	}
	return os.WriteFile(configPath, data, 0644)
}
